package com.hansming.bss.modules.sfc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONException;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hansming.bss.common.config.Global;
import com.hansming.bss.common.web.BaseController;
import com.hansming.bss.modules.sfc.entity.Bannar;
import com.hansming.bss.modules.sfc.entity.CarDatePrice;
import com.hansming.bss.modules.sfc.entity.CarExtr;
import com.hansming.bss.modules.sfc.entity.CarInfo;
import com.hansming.bss.modules.sfc.entity.CarServe;
import com.hansming.bss.modules.sfc.entity.City;
import com.hansming.bss.modules.sfc.entity.Customer;
import com.hansming.bss.modules.sfc.entity.Order;
import com.hansming.bss.modules.sfc.entity.OrderItem;
import com.hansming.bss.modules.sfc.entity.PcUser;
import com.hansming.bss.modules.sfc.entity.Picture;
import com.hansming.bss.modules.sfc.entity.Richtext; 
import com.hansming.bss.modules.sfc.service.BannarService;

import com.hansming.bss.modules.sfc.service.CarExtrService;

import com.hansming.bss.modules.sfc.service.CarDatePriceService;

import com.hansming.bss.modules.sfc.service.CarInfoService;
import com.hansming.bss.modules.sfc.service.CarServeService;
import com.hansming.bss.modules.sfc.service.CityService;
import com.hansming.bss.modules.sfc.service.CustomerService;
import com.hansming.bss.modules.sfc.service.OrderItemService;
import com.hansming.bss.modules.sfc.service.OrderService;
import com.hansming.bss.modules.sfc.service.PcUserService;
import com.hansming.bss.modules.sfc.service.PictureService;
import com.hansming.bss.modules.sfc.service.RichtextService;
import com.hansming.bss.modules.sfc.util.CarTimeHelp;
import com.hansming.bss.modules.sfc.util.PageBean;
import com.hansming.bss.modules.sfc.util.TimeUtil;

import org.springframework.ui.Model;

@Controller
@RequestMapping(value = "/car")
public class CarController extends BaseController{
		
	@Autowired
	private CarInfoService carinfoservice;
	
	@Autowired
	private CarServeService carserveService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private BannarService bannarService;
	

	@Autowired
	private CarExtrService carExtrService;
	

	@Autowired
	private 	CarDatePriceService cardatepriceService;
	
	@Autowired
	private		PictureService	 pictureService;
	
	@Autowired
	private		RichtextService		richtextService;
	

	@Autowired
	private		CustomerService customerService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private CarDatePriceService carDatePriceService;
	
	@Autowired
	private PcUserService pcUserService;
	
	@Autowired
	private OrderItemService orderitemService;
	
	
	//租车首页展示的城市信息
	@RequestMapping(value="/city")
	public void ToCarIndex(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("UTF-8");
		//允许跨域访问
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
	        String code = "1";								//返回前台的消息状态
			String msg = "传递成功";
			List<City> cities = cityService.getCityInhotflag();
			if(cities != null){
				for(City c:cities){
					JSONObject jobj = new JSONObject();
					jobj.put("city", c.getName());
					jobj.put("picture",Global.getBasePath()+c.getPictureUrl());
					datas.put(jobj);
				}
			}
	        jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);			
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/rentlist")
	public String CarInfoList(HttpServletRequest request, HttpServletResponse response,String city,String startDate,String endDate){
		
	
        
        return "modules/sfc/pcsofangche/rent/rentindex/rentindex";//使用接口跳转
	}
	
	
	
	
	//租车搜索的接口
	@RequestMapping(value="/search")
	public void CarInfoListSearch(HttpServletRequest request, HttpServletResponse response,String city,String startDate,String endDate,Integer passengers,String oiltype,String transmission,String drive,Integer bed,Integer sortid,Integer orderid){
		response.setCharacterEncoding("UTF-8");
		//允许跨域访问
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
	        String code = "1";								//返回前台的消息状态
			String msg = "成功";
			if(city == null){//当为null时，设为空值，防止null值影响运行，当前若参数为NULL会在使用方法时候直接出现空指针错误
				city = "";		//城市
			}
			if(drive == null){
				drive = "";	//驱动(现在在PC端或小程序取消驱动相关搜索）
			}
			if(oiltype == null){
				oiltype = "";		//有油耗类型
			}
			if(transmission == null){
				transmission = "";		//手动档还是自动党
			}
			if(sortid == null){
				sortid = 0;
			}		
			if(orderid == null){
				orderid = 0;
			}
			if(bed == null){
				bed =0;
			}
			if(passengers == null){
				passengers = 0;
			}
			List<CarInfo> cars = carinfoservice.findCarListInMiniapp(city, drive, transmission, bed, oiltype, passengers, sortid, orderid);
			for(CarInfo car:cars){
				JSONObject jo = new JSONObject();
				jo.put("id",car.getId());
				jo.put("title",car.getTitle());
				jo.put("price",car.getPrice());
				jo.put("passengers","核载"+car.getPassengers()+"人");
				jo.put("transmission",car.getTransmission());
				jo.put("license", car.getLicense()+"驾照");
				jo.put("bed", "床铺"+car.getBed()+"张");
				jo.put("oilwear", "油耗"+car.getOilwear());
				jo.put("oiltype", car.getOiltype());		
				jo.put("drive", car.getDrive());
				jo.put("info",car.getInfo());
				jo.put("exinfo", car.getExinfo());
				jo.put("img",Global.getBasePath()+car.getShowurl());
				datas.put(jo);
			}		
	        jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}
	
	//租车搜索的接口,更改，能够提供分页信息
		@RequestMapping(value="/searchbypage")
		public void CarInfoListSearchpage(HttpServletRequest request, HttpServletResponse response,String city,String startDate,String endDate,Integer passengers,String oiltype,String transmission,String drive,Integer bed,Integer sortid,Integer orderid,Integer page){
			response.setCharacterEncoding("UTF-8");
			//允许跨域访问
			response.setHeader("Access-Control-Allow-Origin", "*");
	        response.setHeader("Cache-Control", "no-cache");
	        try {
				PrintWriter out = response.getWriter();
				JSONObject jsonObject = new JSONObject(); 
		        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
		        String code = "1";								//返回前台的消息状态
				String msg = "成功";
				if(city == null){//当为null时，设为空值，防止null值影响运行，当前若参数为NULL会在使用方法时候直接出现空指针错误
					city = "";		//城市
				}
				if(drive == null){
					drive = "";	//驱动(现在在PC端或小程序取消驱动相关搜索）
				}
				if(oiltype == null){
					oiltype = "";		//有油耗类型
				}
				if(transmission == null){
					transmission = "";		//手动档还是自动党
				}
				if(sortid == null){
					sortid = 0;
				}		
				if(orderid == null){
					orderid = 0;
				}
				if(bed == null){
					bed =0;
				}
				if(passengers == null){
					passengers = 0;
				}
				PageBean pagebean = new PageBean();			 
		        pagebean.setPage(page);			        
		        pagebean.setPageSize(10);
				List<CarInfo> carsnum = carinfoservice.findCarListInMiniapp(city, drive, transmission, bed, oiltype, passengers, sortid, orderid);
				int num = carsnum.size();
				pagebean.setTotalCount(num);
				List<CarInfo> cars = carinfoservice.findCarListInMiniapppage(city, drive, transmission, bed, oiltype, passengers, sortid, orderid,pagebean);
				for(CarInfo car:cars){
					JSONObject jo = new JSONObject();
					jo.put("id",car.getId());
					jo.put("title",car.getTitle());
					jo.put("price",car.getPrice());
					jo.put("passengers","核载"+car.getPassengers()+"人");
					jo.put("transmission",car.getTransmission());
					jo.put("license", car.getLicense()+"驾照");
					jo.put("bed", "床铺"+car.getBed()+"张");
					jo.put("oilwear", "油耗"+car.getOilwear()+"L/100公里");
					jo.put("oiltype", car.getOiltype());		
					jo.put("drive", car.getDrive());
					jo.put("pickinfo",car.getInfo());
					jo.put("img",Global.getBasePath()+car.getShowurl());
					jo.put("exinfo", car.getExinfo());
					jo.put("city", car.getCity());
					jo.put("bedinfo", car.getBedinfo());
					int t = pagebean.getTotalPage();
					if(t != 0){
						jo.put("totalpage", t);
					}else{
						jo.put("totalpage", 1);
					}
					
					datas.put(jo);
				}		
		        jsonObject.put("code",code);
				jsonObject.put("msg", msg);
				jsonObject.put("data",datas);
				out.print(jsonObject.toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
		}
	
	
	//租车首页接口
	@RequestMapping(value="")
	public String getCarIndex(HttpServletRequest request, HttpServletResponse response,Model model){
		String type = "car";
		//bannar
		List<Bannar> bannars = bannarService.getBannarByType(type);
		model.addAttribute("bannar", bannars);
		//城市图片
		List<City> cities = cityService.selectCityInIndex();
		model.addAttribute("citys", cities);
		return "modules/sfc/pcsofangche/rent/rentindex/rentindex";
	}
	
	
	@RequestMapping(value="/info")
	public void getCarDetailpage(HttpServletRequest request, HttpServletResponse response,String id) {
		//得到指定id标识的车的信息
		System.out.println(id);
		CarInfo car = carinfoservice.get(id);//根据参数id返回一个carInfo实体car,可以使用carInfo里面的任何信息
		CarExtr care = carExtrService.get(car.getCarextr().getId());//有疑问，为什么不可以直接用get(id)方法?表carinfo中id是carid，表carExtr表中的id是表carinfo中的carExtr_id的属性
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONObject datas = new JSONObject();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "传递成功";	
			datas.put("title",car.getTitle());//标题
			datas.put("chassis",care.getChassis());//地盘
			datas.put("brand",car.getBrand());//房车品牌
			datas.put("transmission",car.getTransmission());//变速器
			datas.put("oiltype",car.getOiltype());//燃油类型
			datas.put("oilwear",car.getOilwear());//油耗
			datas.put("passengers",car.getPassengers());//荷载人数
			datas.put("drive",car.getDrive());//驱动模式
			
			
			//
			datas.put("icebox",care.getIcebox());//冰箱
			datas.put("cabAircon",care.getCabAircon());//驾驶室空调
			datas.put("livingAircon",care.getLivingAircon());//起居室空调
			datas.put("equipment",care.getEquipment());//电磁炉
			datas.put("cabHeating",care.getCabHeating());//驾驶室暖气
			datas.put("livingHeating",care.getLivingHeating());//起居室暖气
			datas.put("bed",car.getBed());//床位数
			datas.put("bedinfo",car.getBedinfo());//床位信息
			datas.put("oil",care.getOil());//油箱
			datas.put("water",care.getWater());//水箱
			datas.put("blackwater",care.getBlackwater());//黑水箱
			datas.put("graywater",care.getGraywater());//灰水箱
			datas.put("deposite",care.getDeposite());//车辆押金
			datas.put("foregift",care.getForegift());//违章押金
		
			String photos = care.getPhotos();					
			String[] photolist = photos.split("\\|");
			JSONArray jsa = new JSONArray();
				for(int i=0;i<photolist.length;i++){
					if(i>0 && !"".equals(photolist[i])){
						JSONObject obj = new JSONObject();
						obj.put("picture", Global.getBasePath()+photolist[i]);
						jsa.put(obj);
					}
				}
			datas.put("photos", jsa);
			
			
			JSONArray jss = new JSONArray();
			String[] ids = car.getService().split(",");//[,'2','3']
			for(int i=0;i<ids.length;i++){
				if(!"".equals(ids[i])){//'2'
					ids[i] = ids[i].replace("'", "");//2
					CarServe serve = carserveService.get(ids[i]);
					if(serve!= null){
						JSONObject obj1 = new JSONObject();
						obj1.put("serve", serve.getCaritem());
						jss.put(obj1);
					}
				}
			}
			datas.put("service", jss);
			
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//房车静态服务（例如满油取还）
		String serveids = car.getService();
		String[] ids = serveids.split(",");
		for(int i=0;i<ids.length;i++){
			if(!"".equals(ids[i])){
				ids[i] = ids[i].replace("'", "");
				CarServe serve = carserveService.get(ids[i]);
				if(serve!= null){
//					obj1.put("serve", serve.getCaritem());			
				}
			}

	}
		//价格日历	
		
	}
	
	//根据车辆id和起始时间返回时间，时间请求每日单价
	@RequestMapping(value="/minprice")
	public void rentinfo(HttpServletRequest request, HttpServletResponse response,String startDate,String endDate,String carid) throws UnsupportedEncodingException{
		
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
        	PrintWriter out = response.getWriter();
 			JSONObject jsonObject = new JSONObject(); 
 	        JSONObject datas = new JSONObject();		//返回到前台的具体的价格日期信息json
 	        String code = "1";								//返回前台的消息状态
 			String msg = "访问成功";
 			CarInfo car = carinfoservice.get(carid);//根据参数id返回一个carInfo实体car,可以使用carInfo里面的任何信息		
 			List<CarDatePrice> cardateprice=carDatePriceService.getByDateFrom(startDate, endDate, car);
 			int a=cardateprice.size();
 			int[] dateprice=new int[a];
 			if(cardateprice!=null&&cardateprice.size()>0){
 				for(int i=0;i<a;i++){
 					dateprice[i]=cardateprice.get(i).getPrice().intValue();
 				}
 			}
 			int b=dateprice[0];
 			for(int i=0;i<dateprice.length;i++){
 				if(b>dateprice[i]){
 					b=dateprice[i];
 				};
 			}
 			datas.put("minprice",b);		
 			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}	
	}	
	
	//租车填写订单页面车辆配置信息接口
	@RequestMapping(value="/orderinfo")
	public void orderinfo(HttpServletRequest request, HttpServletResponse response,String carid) throws ParseException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			JSONObject datas = new JSONObject();
	        String code = "1";								//返回前台的消息状态
			String msg = "成功";
			CarInfo car=carinfoservice.get(carid);
			CarExtr care=carExtrService.get(car.getCarextr().getId());
			Integer a=car.getPassengers();
			String a1="荷载"+a+"人";			
			String b=car.getOilwear();
			String b1="";
			if(b.contains("L")){
				b1="油耗"+b+"/100公里";
			}else{
				b1="油耗"+b+"L/100公里";
			};
			int c=car.getBed();
			String c1="床铺"+c+"张";
			String d=car.getLicense()+"驾照";
			String f=care.getPhotos().split("\\|")[1];
			datas.put("title",car.getTitle());
			datas.put("passengers",a1);
			datas.put("oilwear", b1);
			datas.put("transmission",car.getTransmission());
			datas.put("oiltype", car.getOiltype());
			datas.put("license", d);
			datas.put("drive", car.getDrive());
			datas.put("bed", c1);
			datas.put("bedinfo", car.getBedinfo());
			datas.put("showurl", f);
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	@RequestMapping(value="/dateprice")
	public void getpriceinfo(HttpServletRequest request, HttpServletResponse response,String id,Integer year,Integer month,Integer day) throws ParseException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
	        String code = "1";								//返回前台的消息状态
			String msg = "成功";
			Calendar cal = Calendar.getInstance();
	      	cal.set(year, month-1, 1);
	    	int dayNumOfMonth = TimeUtil.getDaysByyearAndday(year, month);  							//返回此月的天数
	      	Date now = new Date(); 																								//得到当前时间
	      	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	      	SimpleDateFormat sdf = new SimpleDateFormat("dd");
	      	
	      	for(int j =0, i = 0;j<42;j++){ 
	      		for (; i < dayNumOfMonth; i++, cal.add(Calendar.DATE, 1)) {      	
	      			if(i==0){
		      			//System.out.println(TimeUtil.getDayBeforeDateInThisWeek(cal.getTime())+"==="+simpleDateFormat.format(cal.getTime()));
		      			int day1 = TimeUtil.getDayBeforeDateInThisWeek(cal.getTime());
		      			for(int n = 0;n<day1;n++,j++){
		      				JSONObject jo = new JSONObject();
		      				jo.put("date", "");
		      				jo.put("price", "");
		      				datas.put(jo);
		      				}
	      				}//	if(i==0){
	      			Date d = cal.getTime();       
	 	            String df = simpleDateFormat.format(d);    //得到此时的日期
	 	            String days = sdf.format(d);
	 	            CarDatePrice carprice = cardatepriceService.getByDate(id, df);
	 	            if(carprice != null){// 如果含有此日的价格
	 	            	if(simpleDateFormat.parse(carprice.getDatetime()).compareTo(simpleDateFormat.parse(simpleDateFormat.format(now))) >= 0){
	 	            		JSONObject jo = new JSONObject();
	 	            		jo.put("date", days);
		      				jo.put("price", carprice.getPrice());
		      				datas.put(jo);
	 	            	}else{
	 	            		JSONObject jo = new JSONObject();
	 	            		jo.put("date", days);
		      				jo.put("price", "");
		      				datas.put(jo);
	 	            	}
	 	            }else{
	 	            	JSONObject jo = new JSONObject();
		      			jo.put("date",days);
	      				jo.put("price", "");
	      				datas.put(jo);
	 	            }
	 	            j++;
	      		}//	for (; i < dayNumOfMonth; i++, cal.add(Calendar.DATE, 1)) {
	      		JSONObject jo = new JSONObject();
	      		jo.put("date","");
  				jo.put("price", "");
  				datas.put(jo);
	      	}	// 	for(int j =0, i = 0;j<42;j++){ 
	      			
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	@RequestMapping(value="/price")
	public void getTotlePriceAndDetail(HttpServletRequest request, HttpServletResponse response,String id,String startDate,String endDate,Integer starttime,Integer endtime,String serveid) throws ParseException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
     			PrintWriter out = response.getWriter();
     			JSONObject jsonObject = new JSONObject(); 
     	        JSONObject datas = new JSONObject();		//返回到前台的具体的价格日期信息json
     	        String code = "1";								//返回前台的消息状态
     			String msg = "访问成功";
     			if(startDate.equals("")){
     				code = "2";
     				msg = "起始日期为空";
     			}else if(endDate.equals("")){
     				code ="2";
     				msg = "还车日期为空";
     			}else if(starttime == null){
     				code = "2";
     				msg= "取车时间为空";
     			}else if(endtime == null){
     				code = "2";
     				msg= "取车时间为空";
     			}else{
     			BigDecimal price = cardatepriceService.getTotlePrice(startDate, endDate, starttime, endtime, id, serveid);
     			datas.put("price",price);
     			}
     			jsonObject.put("code",code);
    			jsonObject.put("msg", msg);
    			jsonObject.put("data",datas);
    			out.print(jsonObject.toString());
    			out.flush();
    			out.close();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
	}
	
	/*
	 * 得到价格详情
	 */
	@RequestMapping(value="/priceinfo")
	public	void		getPriceDetail(HttpServletRequest request, HttpServletResponse response,String id,String startDate,String endDate,Integer starttime,Integer endtime,String serveid){
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
     			
     		
				carserveService.getCarPriceDetai(request, response, startDate, endDate, starttime, endtime, id, serveid);
				
     			
     			
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	}
	
	//得到车辆详情的富文本
		@RequestMapping(value ="/detailinfo")
		public void getcardetailinfo(HttpServletRequest request, HttpServletResponse response,String id) throws IOException{
			response.setCharacterEncoding("UTF-8");
	        response.setHeader("Cache-Control", "no-cache");
	        PrintWriter out = response.getWriter();
	        JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new  JSONArray();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "传递成功";								//返回前台的消息
			CarInfo carinfo = carinfoservice.get(id);
			Picture bannars = pictureService.findpicBytype(carinfo.getTitle());
			if(bannars != null){
				String[] photolist = bannars.getUrl().split("\\|");
				for(int i=0;i<photolist.length;i++){
					if(i>0){
						if(photolist[i] != null && !"".equals(photolist[i])){
							JSONObject obj = new JSONObject();
							obj.put("type","img");
							obj.put("detail", Global.getBasePath()+photolist[i]);
							datas.put(obj);
						}
					}
				}
			}
			jsonObject.put("code", code);
			jsonObject.put("msg", msg);
			jsonObject.put("data", datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		}
	
		
		//得到预定须知的富文本
		@RequestMapping(value ="/preinfo")
		public void getcarpreinfo(HttpServletRequest request, HttpServletResponse response,String id) throws IOException{
			response.setCharacterEncoding("UTF-8");
	        response.setHeader("Cache-Control", "no-cache");
	        PrintWriter out = response.getWriter();
	        JSONObject jsonObject = new JSONObject(); 
	        JSONArray datas = new  JSONArray();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "传递成功";								//返回前台的消息
			List<Richtext> riches = richtextService.getcarsafeRichtextBycarid("only");
			if(riches != null && riches.size()>0){
				for(Richtext r:riches){
					JSONObject jo = new JSONObject();
					jo.put("type", r.getType());
					jo.put("detail", r.getDetail());
					datas.put(jo);
				}
			}
			jsonObject.put("code", code);
			jsonObject.put("msg", msg);
			jsonObject.put("data", datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		}
		
	
		//填写订单
		@RequestMapping(value="/order")
		public void createOrder(HttpServletRequest request, HttpServletResponse response,String startDate,String endDate,Integer starttime,Integer endtime,String id,String serveid,String contactsid,String name,String identtype,String identnum,String email,String phone,String cusmsg,Integer score) throws Exception{
			HttpSession session = request.getSession();
			String token = (String)session.getAttribute("token");
			String  orderid = orderService.createPCUserOrder(request, response, startDate, endDate, starttime, endtime, id, serveid, contactsid, name, identtype, identnum, email, phone, cusmsg, score);
			session.setAttribute("orderid", orderid);
			response.setCharacterEncoding("UTF-8");
	        response.setHeader("Cache-Control", "no-cache");
	        PrintWriter out = response.getWriter();
	        JSONObject jsonObject = new JSONObject(); 
	        JSONObject  datas = new  JSONObject ();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "传递成功";								//返回前台的消息
			try{
				datas.put("orderid", orderid);
				session.setAttribute("orderid", orderid);
			}catch (Exception e) {
				// TODO: handle exception
			}
			jsonObject.put("code", code);
			jsonObject.put("msg", msg);
			jsonObject.put("data", datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
			
		}
		
		//订单详情
		@RequestMapping(value="/payinfo")
		public void payinfo(HttpServletRequest request, HttpServletResponse response,String id) throws Exception{
			response.setCharacterEncoding("UTF-8");
	        response.setHeader("Cache-Control", "no-cache");
	        Order ro=orderService.get(id);
	        CarInfo ci = ro.getCarinfo();
	        CarInfo cai = carinfoservice.get(ci.getId());
	        PrintWriter out = response.getWriter();
	        JSONObject jsonObject = new JSONObject(); 
	        JSONObject  datas = new  JSONObject ();		//返回到前台的具体的价格日期信息json
			String code = "1";								//返回前台的消息状态
			String msg = "传递成功";								//返回前台的消息
			try {
				datas.put("ordernum", ro.getNum());
				datas.put("ordername", cai.getTitle());
				datas.put("price", ro.getPrice());
				datas.put("carname", cai.getTitle());
				datas.put("name", ro.getCname());
				datas.put("phone", ro.getPhone());
				datas.put("picture",Global.getBasePath()+cai.getShowurl());
				if(ro.getEmail().equals("")||ro.getEmail()==null){
					datas.put("email", "未提供邮箱");
				}else{
					datas.put("email", ro.getEmail());
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			jsonObject.put("code", code);
			jsonObject.put("msg", msg);
			jsonObject.put("data", datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
			
		}
		
		//填写订单
				@RequestMapping(value="/orderstate")
				public void orderstate(HttpServletRequest request, HttpServletResponse response,String orderid) throws Exception{
					response.setCharacterEncoding("UTF-8");
			        response.setHeader("Cache-Control", "no-cache");
			        Order ro=orderService.get(orderid);
			        PrintWriter out = response.getWriter();
			        JSONObject jsonObject = new JSONObject(); 
			        JSONObject  datas = new  JSONObject ();		//返回到前台的具体的价格日期信息json
					String code = "1";								//返回前台的消息状态
					String msg = "传递成功";								//返回前台的消息
					try {
						String state = ro.getState();
						if(state!=null){
							if(!state.equals("1")){
								datas.put("state", "success");
							}else{
								datas.put("state", "fail");
							}
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
					
					jsonObject.put("code", code);
					jsonObject.put("msg", msg);
					jsonObject.put("data", datas);
					out.print(jsonObject.toString());
					out.flush();
					out.close();
					System.out.println("66666666666666999999999999999");
				}
				
		//租车详情页可选月份接口，提供近1年的时间月份
		@RequestMapping(value="/rentinfogivemonth")
		public void rentinfogivemonth(HttpServletRequest request, HttpServletResponse response){
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Cache-Control", "no-cache");     
			try {
			 JSONArray datas = new JSONArray();		//返回到前台的具体的价格日期信息json
			 String code = "1";								//返回前台的消息状态
			 String msg = "传递成功";	
			 JSONObject jsonObject = new JSONObject(); 
			 PrintWriter out = response.getWriter();
									
			for(int i =0;i<=12;i++){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				Calendar todatecal = Calendar.getInstance();
				todatecal.add(Calendar.MONTH, i);
				Date date = todatecal.getTime();
				String dated = sdf.format(date);
				JSONObject jo = new JSONObject();
				jo.put("month", dated);
				datas.put(jo);
			}					
			jsonObject.put("code",code);
			jsonObject.put("msg", msg);
			jsonObject.put("data",datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
			} catch (IOException e) {
						
			}
		}
		//租车填写订单页积分接口
		@RequestMapping(value="/rentorderscore")
		public void rentorderscore(HttpServletRequest request, HttpServletResponse response,String token){
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Cache-Control", "no-cache");     
			try {
				JSONObject datas = new JSONObject();		//返回到前台的具体的价格日期信息json
				String code = "1";								//返回前台的消息状态
				String msg = "传递成功";	
				JSONObject jsonObject = new JSONObject(); 
				PrintWriter out = response.getWriter();
				HttpSession session = request.getSession();
				String token1 = (String)session.getAttribute("token");
				PcUser pc = pcUserService.selectAllByToken(token1);
				String userid = pc.getUserid();
				Customer ct = customerService.get(userid);
				int score = ct.getScore();
				datas.put("score", score);
				
				
				jsonObject.put("code",code);
				jsonObject.put("msg", msg);
				jsonObject.put("data",datas);
				out.print(jsonObject.toString());
				out.flush();
				out.close();
				} catch (IOException e) {
								
				}
			}
		
		/**
		 * @param orderid : 订单 id
		 * 根据orderid得到订单信息
		 * @throws IOException 
		 * @throws ParseException 
		 * @throws JSONException 
		 * 
		 * 
		 */
		@RequestMapping(value="/carorderinfo")
		public void getCarOrderInfo(HttpServletResponse response,String orderid) throws IOException, JSONException, ParseException{
			response.setCharacterEncoding("UTF-8");
	        response.setHeader("Content-type", "text/html;charset=UTF-8");
	        PrintWriter out = response.getWriter();
		        JSONObject jsonObject = new JSONObject();
		    JSONObject datas = new  JSONObject();
		        String code = "1";								//返回前台的消息状态
		    String msg = "传输成功";								//返回前台的消息
				Order order = orderService.get(orderid);
		    if(order != null)
		        {
		    		if(order.getType().equals("1")){
		    			CarInfo carinfo = carinfoservice.get(order.getCarinfo().getId());
		    			datas.put("state", order.getState());
		    			datas.put("num",order.getNum() );		
		    			datas.put("name",order.getCname() );
		    			datas.put("imgurl", Global.getBasePath()+carinfo.getShowurl());
		    			datas.put("title", carinfo.getTitle());
		    			datas.put("cusmsg", order.getCusmsg());
		    			
		    			datas.put("transmission", carinfo.getTransmission());
		    			datas.put("passengers", carinfo.getPassengers());
		    			datas.put("bed",carinfo.getBed());
		    			datas.put("oilwear",carinfo.getOilwear());
		    			datas.put("oiltype",carinfo.getOiltype());
		    			datas.put("drive",carinfo.getDrive());
		    			datas.put("license",carinfo.getLicense());
		    			
		    			
		    			
		    			
		    			datas.put("city",carinfo.getCity());
		    			datas.put("begindate",order.getBeginDate());
		    			datas.put("beginday",TimeUtil.getweekday(order.getBeginDate()));
		    			datas.put("enddate",order.getEndDate());
		    			datas.put("endday",TimeUtil.getweekday(order.getEndDate()));
		    			datas.put("begintime", CarTimeHelp.changetotime(order.getBegintime()));
		    			datas.put("endtime", CarTimeHelp.changetotime(order.getEndtime()));
		    			datas.put("email", order.getEmail());
		    			datas.put("phone",order.getPhone());
		    			datas.put("cusmsg", order.getCus_msg());
		    			List<OrderItem> lo = orderitemService.getOrderItemsByOrderId(orderid);
		    			
		    			JSONArray ja = new JSONArray();
		    			//需要先展示订单详情中车辆租金，最后展示积分抵扣
		    			for(OrderItem oi:lo){
		    				if("车辆租金".equals(oi.getItemname())){
		    					JSONObject jsono = new JSONObject();
		    					jsono.put("name", oi.getItemname());
		    					jsono.put("price", "￥"+oi.getItemprice());
		    					ja.put(jsono);
		    				}
		    			}
		    			for(OrderItem oi:lo){
		    				if(!"车辆租金".equals(oi.getItemname()) &&  !"积分抵扣".equals(oi.getItemname())){
		    					JSONObject jsono = new JSONObject();
		    					jsono.put("name", oi.getItemname());
		    					jsono.put("price", "￥"+oi.getItemprice());
		    					ja.put(jsono);
		    				}
		    			}
		    			for(OrderItem oi:lo){
		    				if("积分抵扣".equals(oi.getItemname())){
		    					JSONObject jsono = new JSONObject();
		    					jsono.put("name", oi.getItemname());
		    					jsono.put("price","-￥"+ oi.getItemprice());
		    					ja.put(jsono);
		    				}
		    			}
		    			datas.put("orderdetail",ja);
		    			datas.put("price", order.getPrice());
		    			
		    			
		    		}else{
		    			code="2";
		    			msg = "订单获取类别错误";
		    		}
		        }else{
		        	code ="2";
		        	msg = "订单获取失败请联系客服人员！";
		        }
			jsonObject.put("code", code);
			jsonObject.put("msg", msg);
			jsonObject.put("data", datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		
		}
}
